/**
 * Spatialytics_test.js
 *
 * JavaScript used for test page of Spatialytics app
 *
 * Copyright (C) 2008-2009 GeoSOA Research Group, Universite Laval
 * See LICENSE file under this distribution for licensing information
 * 
 * @author Etienne Dube
 * @since 200807 
 * @author Vincent Plantegenet
 * @since 201003
 **/

// include Spatialytics modules
// dojo.registerModulePath("GeoSOA","../../GeoSOA");
dojo.require("GeoSOA.olap4js.OlapAjax");
dojo.require("GeoSOA.Spatialytics.SOLAPContext");
dojo.require("GeoSOA.Spatialytics.mapstyles.MapStyle");
dojo.require("GeoSOA.Spatialytics.mapstyles.contexts.IntervalsThematicContext");
dojo.require("GeoSOA.Spatialytics.mapstyles.contexts.EqualIntervalsThematicContext");
dojo.require("GeoSOA.Spatialytics.mapstyles.contexts.DynamicProportionalSymbolsThematicContext");

dojo.require("dojox.xml.DomParser");

dojo.require("AtolCD.Spatialytics.DialogManager");

var spatialyticsTestApp = {
	solapContext: null,
	init: function () {
		var that = this;
		
		var onLoadFunction = function () {

			//Load a json general conf file
			
			var config ;
			
			//The parameters to pass to xhrGet, the url, how to handle it, and the callbacks.
			var xhrArgs = {
				url: "conf.json",
				sync: true,//Need to wait the file to continue
				load: function(data){},
				error: function(error){}
			}

			//Call the asynchronous xhrGet
			var deferred = dojo.xhrGet(xhrArgs);
			
			//parse json into obj
			config = dojo.fromJson(deferred.results[0]);

			
			//console.log(jsdom);
			// instantiate an OpenLayers Map, drawn in <div> with id 'map'
			var options = {
							  //projection: new OpenLayers.Projection("EPSG:27572"),
							  //displayProjection: new OpenLayers.Projection("EPSG:27572"),
							  //units: "m",
							  //numZoomLevels: 20,
							  //maxResolution: 156.0339,
							  //maxExtent: new OpenLayers.Bounds(-20037508, -20037508, 20037508, 20037508.34)
							};

			var theMap = new OpenLayers.Map('map', options);
			
			vlayer = new OpenLayers.Layer.Vector( "Editable" );//Unused, needed for future purpose (polygon sel.)
			
			// add a base layer (world map) from a WMS service
			var wms = new OpenLayers.Layer.WMS( "OpenLayers WMS","http://labs.metacarta.com/wms/vmap0", {layers: 'basic'} );
			
			theMap.addControl(new OpenLayers.Control.LayerSwitcher());
			theMap.addLayer(wms);
			
			// instantiate the OlapAjax object
			// (which is responsible of querying the Spatialytics server
			// and making the resulting CellSet data available through the
			// olap4js API)
			var mdxQueryEditor = dijit.byId("mdxQueryEditor"); 
			mdxQueryEditor.mdxQuery = config.app.initreq;

			var olapAjax = new GeoSOA.olap4js.OlapAjax(
					{
						olapJSONServiceURL: "SpatialyticsServlet",
						mdxQuery: config.app.initreq//get parser and set object inside for querying at the first load
					}
			);
			
			// instantiate the SOLAPContext object
			// (which is responsible of creating and refreshing an
			// OpenLayers vector layer with the SOLAP data from an OlapAjax
			// object)
			that.solapContext = new GeoSOA.Spatialytics.SOLAPContext(
					{
						olapAjax: olapAjax,
						mapRef : theMap,
						solapToolbarDOMNode: dojo.byId("solapToolbar"),
						displayAreaDOMNode: dojo.byId("displayArea"),
						projection: new OpenLayers.Projection("EPSG:4326"),
						jpurl: config.app.jpivoturl,
						conf : config,
						vlayer : vlayer
					}
			);

			// Featurizer objects
			var polygonFeaturizer = new GeoSOA.Spatialytics.Featurizer(
					{ geomProperty: "geom" } );
			var pointFeaturizer = new GeoSOA.Spatialytics.Featurizer(
					{ geomProperty: "pointgeom" } );
			/*var pointFeaturizer = new GeoSOA.Spatialytics.Featurizer(
					{ geomProperty: "pointgeom" } );*/
			// define MapStyle object
			var equalIntervalsMapStyle = new GeoSOA.Spatialytics.mapstyles.MapStyle(
					{
						featurizer: polygonFeaturizer,
						thematicContext:
							new GeoSOA.Spatialytics.mapstyles.contexts.EqualsIntervalsThematicContext(
									{
										valueAttribute: "value",
										solapContext: that.solapContext,
										numberOfIntervals: config.map.intervals,
										minValue: 0,
										maxValue: 2000000,
										minColor: config.map.minCol,
										maxColor: config.map.maxCol,
										linear:true
									}
							)
					}
			);
			
			var dynamicProportionalSymbolsMapStyle = new GeoSOA.Spatialytics.mapstyles.MapStyle(
						{
							featurizer: pointFeaturizer,
							thematicContext: new GeoSOA.Spatialytics.mapstyles.contexts.DynamicProportionalSymbolsThematicContext(
									{
										valueAttribute: "value",
										solapContext: that.solapContext,
										minSize: 5,
										maxSize: 20
									}
							),
							thematicSymbolizer: {
								fillOpacity: 0.9,
								strokeColor: "#555555",
								strokeWidth: 1,
								fillColor: "${getColor}",
								pointRadius: "${getSize}"
							}
						}
				);
	
			// sets the style for the vector layer
			that.solapContext.setMapStyle(equalIntervalsMapStyle);
			//that.solapContext.setMapStyle(dynamicProportionalSymbolsMapStyle);
			
			// attach the ThematicStyleChooser widget to the SOLAPContext,
			// so the StyleMap is set when changing it in the widget
			//thematicStyleChooser.attachSOLAPContext(that.solapContext);
			
			// attach the MDXQueryEditor widget to the OlapAjax
			mdxQueryEditor.attachOlapAjax(olapAjax, true);
			
			//Datadisplayer
			var dataDisplayer = dijit.byId("dataDisplayer");
			dataDisplayer.attachSOLAPContext(that.solapContext);

			//legend displayer
			var legendDisplayer = dijit.byId("legendDisplayer");
			
			// Ajouter un observable, registeer legend displayer ?
			legendDisplayer.attachStyle(equalIntervalsMapStyle);
			legendDisplayer.attachSOLAPContext(that.solapContext);
			
			//var chooser
			var measureChooser = dijit.byId("measureChooser");
			measureChooser.attachOlapAjax(olapAjax, true);
			measureChooser.attachSOLAPContext(that.solapContext);
			
			//var FilterTree, 
			var filterTree = dijit.byId("filterTree");
			filterTree.attachOlapAjax(olapAjax);
			filterTree.attachSOLAPContext(that.solapContext);
			filterTree.initialize(config);
			
			//Manager for Waiting dialogs
			var dialMan = new AtolCD.Spatialytics.DialogManager({onObs:olapAjax.newRequest,offObs:olapAjax.afterResponseObservable,message:"Requesting Mondrian..."});

			// submit the initial MDX query on page load
			dojo.addOnLoad(olapAjax.getSubmitQueryClosure());
		
			// add the SOLAP vector layer to the map
			theMap.addLayer(that.solapContext.vectorLayer);
			
			
			theMap.addLayer(vlayer);
			
			// control for selection of SOLAP features (for)
			var selectControl = that.solapContext.getOpenLayersSelectControl(0);
			theMap.addControl(selectControl);
			var noSelectControl = that.solapContext.getOpenLayersSelectControl(1);
			theMap.addControl(noSelectControl);
			var detailsCtrl = that.solapContext.getOpenLayersSelectControl(2);
			theMap.addControl(detailsCtrl);
			
			detailsCtrl.activate();
		
			// control for handling click events on SOLAP features
			var clickControl = that.solapContext.getOpenLayersClickControl();
			theMap.addControl(clickControl);
			clickControl.activate();
		
			// Zoom to the approx. extent of France:
			theMap.zoomToExtent(
					new OpenLayers.Bounds(-6, 51, 10, 43)//
			); 

			zb = new OpenLayers.Control.ZoomBox(
			{title:"Zoom box: Selecting it you can zoom on an area by clicking and dragging."});
			sel = new OpenLayers.Control.MouseDefaults({name: 'default', title:'You can use the default mouse configuration'});
			
			var panel = new OpenLayers.Control.Panel({'id':'ctrlPan','div':OpenLayers.Util.getElement('paneldiv'),direction:'horizontal',defaultControl: sel});
			panel.addControls([
			sel, 
			zb,
			new OpenLayers.Control.ZoomOut({title:'Zoom -'}),
			new OpenLayers.Control.ZoomIn({title:'Zoom +'}),/**
			new OpenLayers.Control.DrawFeature(vlayer, OpenLayers.Handler.Polygon,
			{title:'Draw a feature'}),**/
			new OpenLayers.Control.Navigation({title:"Navigate"}) 
			]);
			theMap.addControl(panel);

			// resize the map div (needed after initialization of Dojo toolbar)
			theMap.updateSize();
		};
		
		//defer initialization of the Spatialytics app until the page is loaded:
		dojo.addOnLoad(onLoadFunction);
	}
};

spatialyticsTestApp.init();
